//
//  RequestPlugins.swift
//  Lease_IOS
//
//  Created by Mr.wang on 2018/12/20.
//  Copyright © 2018 Mr.wang. All rights reserved.
//

import Moya

struct ApiEncryptionPlugin: PluginType {
    
    func prepare(_ request: URLRequest, target: TargetType) -> URLRequest {
        var newRequest = request
        if let data = request.httpBody {
            print(String.init(data: data, encoding: .utf8))
            newRequest.httpBody = ApiEncryption.shared.encryptionRequestData(data)
        }
        if var header = request.allHTTPHeaderFields {
            header["encrypted"] = ApiEncryption.shared.rsa()
            newRequest.allHTTPHeaderFields = header
        }
        return newRequest
    }
    
}

struct RequestErrorPlugin: PluginType {
    
    func didReceive(_ result: Result<Response, MoyaError>, target: TargetType) {
        var message = ""
        let newResult = result.decode()
        if case let Result.success(response) = newResult {
            if response.code == 200 {
                return
            } else if response.code == 401 {
                let alert = UIAlertController.init(title: "系统提示".localized, message: response.msg, preferredStyle: .alert)
                alert.addAction(UIAlertAction.init(title: "确定".localized, style: .cancel, handler: { _ in
                    let vc = MainNavigationViewController.init(rootViewController: LoginViewController(type: .login))
                    UIApplication.shared.keyWindow?.setRootViewController(vc, type: .push)
                }))
                UIApplication.shared.keyWindow?.rootViewController?.present(alert, animated: true, completion: nil)
                APPUser.shared.state = .logOut
                return
            } else {
                message = response.msg
            }
        } else if case let Result.failure(error) = newResult {
            if error.isCancelled { return }
            message = error.errorDescription ?? "服务器异常".localized
        }
        APPHud.shared.showError(status: message)
    }
    
}

class RequestLogPlugin: PluginType {
    
    func didReceive(_ result: Result<Response, MoyaError>, target: TargetType) {
        let newResult = result.decode()
        #if DEBUG
        print("\n\n++++++++++++++++++++++++++++++++++++++++++++++++")
        switch newResult {
        case .success(let response):
            print("url:   ", response.request?.url?.absoluteString ?? "")
            print("header:   ",response.request?.allHTTPHeaderFields ?? [:])
            if let data = response.request?.httpBody,
                let para = String.init(data: data, encoding: .utf8) {
                print("parameters:   ", para)
            }
            if let data = try? JSONSerialization.data(withJSONObject: response.jsonDictionary, options: JSONSerialization.WritingOptions.prettyPrinted),
                let string = String.init(data: data, encoding: String.Encoding.utf8),
                response.code != 9999 {
                print("success：", string.replacingOccurrences(of: "\\/", with: "/"))
            } else if let json = try? response.mapString() {
                print("failure：", json)
            }
        case .failure(let error):
            print("failure：", error.errorDescription ?? "")
        }
        print("++++++++++++++++++++++++++++++++++++++++++++++++\n\n")
        #endif
    }
    
}
